import React, { useState, useEffect, useRef } from 'react';
import { Card, Row, Col, Button, Modal, Input, message, Tag, Avatar, Tooltip, Space } from 'antd';
import { PlusOutlined, EyeOutlined, CopyOutlined, EditOutlined, DeleteOutlined, UserOutlined } from '@ant-design/icons';
import dayjs from 'dayjs';
import BpmnViewer from 'bpmn-js/lib/NavigatedViewer';

interface ProcessTemplate {
  id: string;
  name: string;
  description: string;
  category: string;
  xml: string;
  svg?: string;
  thumbnail?: string;
  author: string;
  authorName: string;
  createdAt: string;
  updatedAt: string;
  usageCount: number;
  tags: string[];
  isPublic: boolean;
}

interface ProcessTemplatesProps {
  onSelectTemplate?: (template: ProcessTemplate) => void;
  onCreateFromTemplate?: (template: ProcessTemplate) => void;
}

const ProcessTemplates: React.FC<ProcessTemplatesProps> = ({
  onSelectTemplate,
  onCreateFromTemplate
}) => {
  const [templates, setTemplates] = useState<ProcessTemplate[]>([]);
  const [loading, setLoading] = useState(false);
  const [previewVisible, setPreviewVisible] = useState(false);
  const [selectedTemplate, setSelectedTemplate] = useState<ProcessTemplate | null>(null);
  const [searchText, setSearchText] = useState('');
  const [selectedCategory, setSelectedCategory] = useState<string>('all');
  const viewerRef = useRef<BpmnViewer | null>(null);
  const viewerContainerRef = useRef<HTMLDivElement>(null);

  // 模拟模板数据
  const mockTemplates: ProcessTemplate[] = [
    {
      id: '1',
      name: '请假审批流程',
      description: '标准的请假申请审批流程，包含申请、主管审批、HR审批等环节',
      category: '人事管理',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="LeaveApprovalProcess" name="请假审批流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="提交请假申请" />
    <bpmn:userTask id="ManagerApproval" name="主管审批" />
    <bpmn:userTask id="HRApproval" name="HR审批" />
    <bpmn:endEvent id="EndEvent_1" name="审批完成" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'admin',
      authorName: '系统管理员',
      createdAt: '2024-01-15T10:00:00Z',
      updatedAt: '2024-01-20T15:30:00Z',
      usageCount: 156,
      tags: ['人事', '审批', '请假'],
      isPublic: true
    },
    {
      id: '2',
      name: '采购申请流程',
      description: '企业采购申请审批流程，支持多级审批和预算控制',
      category: '采购管理',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="PurchaseApprovalProcess" name="采购申请流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="提交采购申请" />
    <bpmn:exclusiveGateway id="AmountGateway" name="金额判断" />
    <bpmn:userTask id="ManagerApproval" name="部门经理审批" />
    <bpmn:userTask id="FinanceApproval" name="财务审批" />
    <bpmn:endEvent id="EndEvent_1" name="采购完成" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'user001',
      authorName: '张三',
      createdAt: '2024-01-10T09:00:00Z',
      updatedAt: '2024-01-18T14:20:00Z',
      usageCount: 89,
      tags: ['采购', '审批', '财务'],
      isPublic: true
    },
    {
      id: '3',
      name: '报销审批流程',
      description: '员工报销申请审批流程，包含费用审核和财务付款环节',
      category: '财务管理',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="ExpenseReimbursementProcess" name="报销审批流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="提交报销申请" />
    <bpmn:userTask id="ManagerReview" name="主管审核" />
    <bpmn:userTask id="FinanceReview" name="财务审核" />
    <bpmn:userTask id="Payment" name="财务付款" />
    <bpmn:endEvent id="EndEvent_1" name="报销完成" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'user002',
      authorName: '李四',
      createdAt: '2024-01-12T11:30:00Z',
      updatedAt: '2024-01-22T16:45:00Z',
      usageCount: 234,
      tags: ['报销', '财务', '审核'],
      isPublic: true
    },
    {
      id: '4',
      name: '客户服务流程',
      description: '客户投诉处理和服务请求流程，包含分类、处理、回访等环节',
      category: '客户服务',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="CustomerServiceProcess" name="客户服务流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="客户请求" />
    <bpmn:userTask id="Classification" name="问题分类" />
    <bpmn:userTask id="Processing" name="问题处理" />
    <bpmn:userTask id="FollowUp" name="客户回访" />
    <bpmn:endEvent id="EndEvent_1" name="服务完成" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'user003',
      authorName: '王五',
      createdAt: '2024-01-08T14:15:00Z',
      updatedAt: '2024-01-25T10:20:00Z',
      usageCount: 67,
      tags: ['客服', '投诉', '服务'],
      isPublic: true
    },
    {
      id: '5',
      name: '项目审批流程',
      description: '项目立项审批流程，包含需求评估、资源分配、风险评估等环节',
      category: '项目管理',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="ProjectApprovalProcess" name="项目审批流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="项目申请" />
    <bpmn:userTask id="RequirementReview" name="需求评估" />
    <bpmn:userTask id="ResourceAllocation" name="资源分配" />
    <bpmn:userTask id="RiskAssessment" name="风险评估" />
    <bpmn:userTask id="FinalApproval" name="最终审批" />
    <bpmn:endEvent id="EndEvent_1" name="项目启动" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'user004',
      authorName: '赵六',
      createdAt: '2024-01-05T16:00:00Z',
      updatedAt: '2024-01-20T09:30:00Z',
      usageCount: 45,
      tags: ['项目', '审批', '管理'],
      isPublic: true
    },
    {
      id: '6',
      name: '合同审批流程',
      description: '合同签署审批流程，包含法务审核、财务审核、领导审批等环节',
      category: '法务管理',
      xml: `<?xml version="1.0" encoding="UTF-8"?>
<bpmn:definitions xmlns:bpmn="http://www.omg.org/spec/BPMN/20100524/MODEL">
  <bpmn:process id="ContractApprovalProcess" name="合同审批流程" isExecutable="true">
    <bpmn:startEvent id="StartEvent_1" name="合同申请" />
    <bpmn:userTask id="LegalReview" name="法务审核" />
    <bpmn:userTask id="FinanceReview" name="财务审核" />
    <bpmn:userTask id="LeadershipApproval" name="领导审批" />
    <bpmn:userTask id="ContractSigning" name="合同签署" />
    <bpmn:endEvent id="EndEvent_1" name="合同生效" />
  </bpmn:process>
</bpmn:definitions>`,
      author: 'user005',
      authorName: '孙七',
      createdAt: '2024-01-03T13:45:00Z',
      updatedAt: '2024-01-19T11:15:00Z',
      usageCount: 78,
      tags: ['合同', '法务', '审批'],
      isPublic: true
    }
  ];

  useEffect(() => {
    loadTemplates();
  }, []);

  const loadTemplates = async () => {
    setLoading(true);
    try {
      // 模拟API调用
      await new Promise(resolve => setTimeout(resolve, 500));
      setTemplates(mockTemplates);
    } catch (error) {
      message.error('加载模板失败');
    } finally {
      setLoading(false);
    }
  };

  const handlePreview = (template: ProcessTemplate) => {
    setSelectedTemplate(template);
    setPreviewVisible(true);
  };

  // 初始化BPMN查看器
  const initBpmnViewer = async () => {
    if (viewerContainerRef.current && selectedTemplate) {
      try {
        // 清理之前的查看器
        if (viewerRef.current) {
          viewerRef.current.destroy();
        }

        // 创建新的查看器
        viewerRef.current = new BpmnViewer({
          container: viewerContainerRef.current,
          width: '100%',
          height: '300px'
        });

        // 导入BPMN XML
        await viewerRef.current.importXML(selectedTemplate.xml);
        
        // 自适应画布
        const canvas = viewerRef.current.get('canvas');
        canvas.zoom('fit-viewport');
      } catch (error) {
        console.error('BPMN预览失败:', error);
        message.error('流程图预览失败');
      }
    }
  };

  // 当预览模态框打开且有选中模板时，初始化查看器
  useEffect(() => {
    if (previewVisible && selectedTemplate) {
      // 延迟初始化，确保DOM已渲染
      setTimeout(initBpmnViewer, 100);
    }
    
    // 清理函数
    return () => {
      if (viewerRef.current) {
        viewerRef.current.destroy();
        viewerRef.current = null;
      }
    };
  }, [previewVisible, selectedTemplate]);

  const handleUseTemplate = (template: ProcessTemplate) => {
    onCreateFromTemplate?.(template);
    message.success(`已使用模板：${template.name}`);
  };

  const handleCopyTemplate = (template: ProcessTemplate) => {
    // 复制模板逻辑
    message.success(`模板已复制：${template.name}`);
  };

  // 获取分类列表
  const categories = ['all', ...Array.from(new Set(templates.map(t => t.category)))];

  // 过滤模板
  const filteredTemplates = templates.filter(template => {
    const matchesSearch = template.name.toLowerCase().includes(searchText.toLowerCase()) ||
                         template.description.toLowerCase().includes(searchText.toLowerCase()) ||
                         template.tags.some(tag => tag.toLowerCase().includes(searchText.toLowerCase()));
    const matchesCategory = selectedCategory === 'all' || template.category === selectedCategory;
    return matchesSearch && matchesCategory;
  });

  const getCategoryColor = (category: string) => {
    const colors: Record<string, string> = {
      '人事管理': 'blue',
      '采购管理': 'green',
      '财务管理': 'orange',
      '客户服务': 'purple',
      '项目管理': 'cyan',
      '法务管理': 'red'
    };
    return colors[category] || 'default';
  };

  return (
    <div className="process-templates">
      {/* 搜索和筛选 */}
      <div style={{ marginBottom: 16 }}>
        <Row gutter={16}>
          <Col span={12}>
            <Input.Search
              placeholder="搜索模板名称、描述或标签"
              value={searchText}
              onChange={(e) => setSearchText(e.target.value)}
              style={{ width: '100%' }}
            />
          </Col>
          <Col span={8}>
            <select
              value={selectedCategory}
              onChange={(e) => setSelectedCategory(e.target.value)}
              style={{ width: '100%', height: 32, border: '1px solid #d9d9d9', borderRadius: 6, padding: '0 8px' }}
            >
              <option value="all">全部分类</option>
              {categories.filter(c => c !== 'all').map(category => (
                <option key={category} value={category}>{category}</option>
              ))}
            </select>
          </Col>
          <Col span={4}>
            <Button type="primary" icon={<PlusOutlined />} block>
              创建模板
            </Button>
          </Col>
        </Row>
      </div>

      {/* 模板列表 */}
      <Row gutter={[16, 16]}>
        {filteredTemplates.map(template => (
          <Col key={template.id} xs={24} sm={12} lg={8} xl={6}>
            <Card
              hoverable
              size="small"
              cover={
                <div style={{ 
                  height: 120, 
                  background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  color: 'white',
                  fontSize: 16,
                  fontWeight: 'bold'
                }}>
                  {template.name}
                </div>
              }
              actions={[
                <Tooltip title="预览">
                  <EyeOutlined onClick={() => handlePreview(template)} />
                </Tooltip>,
                <Tooltip title="使用模板">
                  <CopyOutlined onClick={() => handleUseTemplate(template)} />
                </Tooltip>,
                <Tooltip title="复制模板">
                  <EditOutlined onClick={() => handleCopyTemplate(template)} />
                </Tooltip>
              ]}
            >
              <Card.Meta
                title={
                  <div>
                    <div style={{ marginBottom: 4 }}>{template.name}</div>
                    <Tag color={getCategoryColor(template.category)}>
                      {template.category}
                    </Tag>
                  </div>
                }
                description={
                  <div>
                    <div style={{ 
                      fontSize: 12, 
                      color: '#666', 
                      marginBottom: 8,
                      height: 32,
                      overflow: 'hidden',
                      display: '-webkit-box',
                      WebkitLineClamp: 2,
                      WebkitBoxOrient: 'vertical'
                    }}>
                      {template.description}
                    </div>
                    
                    <div style={{ marginBottom: 8 }}>
                      {template.tags.slice(0, 3).map(tag => (
                        <Tag key={tag} style={{ fontSize: 10 }}>
                          {tag}
                        </Tag>
                      ))}
                      {template.tags.length > 3 && (
                        <Tag style={{ fontSize: 10 }}>+{template.tags.length - 3}</Tag>
                      )}
                    </div>
                    
                    <div style={{ 
                      display: 'flex', 
                      justifyContent: 'space-between', 
                      alignItems: 'center',
                      fontSize: 11,
                      color: '#999'
                    }}>
                      <div>
                        <Avatar size={16} icon={<UserOutlined />} style={{ marginRight: 4 }} />
                        {template.authorName}
                      </div>
                      <div>使用 {template.usageCount} 次</div>
                    </div>
                  </div>
                }
              />
            </Card>
          </Col>
        ))}
      </Row>

      {/* 预览模态框 */}
      <Modal
        title={`模板预览 - ${selectedTemplate?.name}`}
        open={previewVisible}
        onCancel={() => setPreviewVisible(false)}
        width={800}
        footer={[
          <Button key="cancel" onClick={() => setPreviewVisible(false)}>
            关闭
          </Button>,
          <Button key="use" type="primary" onClick={() => {
            if (selectedTemplate) {
              handleUseTemplate(selectedTemplate);
              setPreviewVisible(false);
            }
          }}>
            使用此模板
          </Button>
        ]}
      >
        {selectedTemplate && (
          <div>
            <div style={{ marginBottom: 16 }}>
              <h4>模板信息</h4>
              <p><strong>分类：</strong>{selectedTemplate.category}</p>
              <p><strong>描述：</strong>{selectedTemplate.description}</p>
              <p><strong>作者：</strong>{selectedTemplate.authorName}</p>
              <p><strong>创建时间：</strong>{dayjs(selectedTemplate.createdAt).format('YYYY-MM-DD HH:mm')}</p>
              <p><strong>使用次数：</strong>{selectedTemplate.usageCount}</p>
              <div>
                <strong>标签：</strong>
                {selectedTemplate.tags.map(tag => (
                  <Tag key={tag} style={{ marginLeft: 4 }}>{tag}</Tag>
                ))}
              </div>
            </div>
            
            <div style={{ marginBottom: 16 }}>
              <h4>流程预览</h4>
              <div 
                ref={viewerContainerRef}
                style={{
                  height: 300,
                  border: '1px solid #d9d9d9',
                  borderRadius: 4,
                  background: '#fafafa'
                }}
              />
            </div>
            
            <div>
              <h4>BPMN XML</h4>
              <Input.TextArea
                value={selectedTemplate.xml}
                rows={8}
                readOnly
                style={{ fontFamily: 'monospace', fontSize: 12 }}
              />
            </div>
          </div>
        )}
      </Modal>
    </div>
  );
};

export default ProcessTemplates;